package com.yswy.app.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.response.AlipayTradePayResponse;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.yswy.app.service.AgreementOrderPayLogService;
import com.yswy.app.service.AgreementOrderService;
import com.yswy.app.service.SysConfigService;
import com.yswy.app.service.UserJlAdLogService;
import com.yswy.common.enums.CsjJlAdEnums;
import com.yswy.common.enums.DateUnitEnums;
import com.yswy.common.utils.DateUtils;
import com.yswy.common.utils.StringUtils;
import com.yswy.domain.entity.AgreementOrder;
import com.yswy.domain.entity.AgreementOrderPayLog;
import com.yswy.domain.entity.PayOrder;
import com.yswy.domain.entity.UserJlAdLog;
import com.yswy.domain.mapper.AgreementOrderPayLogMapper;
import com.yswy.domain.mapper.UserJlAdLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.CRC32;

@Service
@Slf4j
public class UserJlAdLogServiceImpl extends ServiceImpl<UserJlAdLogMapper, UserJlAdLog>
        implements UserJlAdLogService {

    @Autowired
    private SysConfigService sysConfigService ;
    @Override
    public String saveUserJlAdLog(UserJlAdLog userJlAdLog) {
        String mKey =sysConfigService.selectConfigByKey("sys.csj.jlSing");// "4fb2e8ef6f2a776d2fe253aa4242bf09" ;
        String singStr = mKey+":"+userJlAdLog.getTransId();
        String sing = getSHA256Str(singStr);
        try {
            JSONObject jsonObject = JSONObject.parseObject(userJlAdLog.getExtra());
            if (userJlAdLog.getSign().equals(sing)){
                CRC32 selectIDCrc32 = new CRC32();
                String selectIDStr  = userJlAdLog.getTransId()+userJlAdLog.getUserId() ;
                selectIDCrc32.update(selectIDStr.getBytes());
                if (count(new LambdaQueryWrapper<UserJlAdLog>().eq(UserJlAdLog::getSelectId , selectIDCrc32.getValue())) == 0){
                    userJlAdLog.setSelectId(selectIDCrc32.getValue());
                    userJlAdLog.setLookType(jsonObject.getString("type"));
                    save(userJlAdLog);
                }
                return "{\"is_verify\": true,\"reason\" : 0}";
            }else {
                return "{\"is_verify\": false,\"reason\" : -100}";
            }
        }catch (Exception e){
            return "{\"is_verify\": false,\"reason\" : -100}";
        }

    }

    @Override
    public Boolean usdUserJlAdLog(Long userId, String transId , String lookType) {
        //判断是否开启广告验证
        Integer isOpen =Integer.parseInt(sysConfigService.selectConfigByKey("sys.usdUserJlAdLog"));
        if (isOpen == 0){
            return true ;
        }
        if (lookType.equals( CsjJlAdEnums.WYJCPLAYLOOK.getMessage())){
            //午夜剧场验证看广告解锁次数
            Integer lookNumMax =Integer.parseInt(sysConfigService.selectConfigByKey("sys.WYJCPLAYLOOK.lookNumMax"));
            Integer lookNum  = count(new LambdaQueryWrapper<UserJlAdLog>()
                    .eq(UserJlAdLog::getLookType ,lookType )
                    .eq(UserJlAdLog::getUserId , userId)
                    .last("and to_days(now()) - to_days(create_time) = 0"));
            if (lookNum > lookNumMax){
                throw new IllegalStateException("当日看视频解锁次数已达上限");
            }
        }


        CRC32 selectIDCrc32 = new CRC32();
        String selectIDStr  = transId+userId ;
        selectIDCrc32.update(selectIDStr.getBytes());
        UserJlAdLog userJlAdLog = getOne(new LambdaQueryWrapper<UserJlAdLog>()
                .eq(UserJlAdLog::getSelectId ,selectIDCrc32.getValue())
                .eq(UserJlAdLog::getIsReceive , false)
                .eq(UserJlAdLog::getLookType , lookType));
        if (userJlAdLog == null){
            return false ;
        }else {
            userJlAdLog.setIsReceive(true);
            updateById(userJlAdLog);
            return true ;
        }
    }


    public static void main(String[] args) {
        String mKey = "4fb2e8ef6f2a776d2fe253aa4242bf09" ;
        String singStr = mKey+":2e8ca63e-ba52-472b-ba68-4d9cf5f80b64";
        String s = getSHA256Str(singStr);
        System.out.println(s);
    }
    /***
     * 利用Apache的工具类实现SHA-256加密
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256Str(String str){
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }
}
